from selenium import webdriver
import time
import os

# 配置下载路径
options = webdriver.ChromeOptions()
# 下载目录使用os.getcwd()设置当前目录作为保存位置
prefs = {
    'download.default_directory': os.getcwd(),  # 下载文件 保存在同级目录
    'profile.default_content_setting_values.automatic_downloads': 1  # 允许下载多个文件
}
# 添加到配置里
options.add_experimental_option('prefs', prefs)

# 创建webdriver实例对象
browser = webdriver.Chrome(options=options)
# 输入爬取网址
url = 'https://www.doc88.com/p-3651708817002.html'
# 输入爬取页数   也就是多少张pdf
pages = 18
# 请求页面
browser.get(url)

time.sleep(3)
# 点击id按钮 continueButton
continueButton = browser.find_element_by_id('continueButton')

# 点击按钮
continueButton.click()

# 滚动到页面底部
browser.execute_script('window.scrollTo(0, document.body.scrollHeight)')

# 调用函数scroll将左侧的滚动条滑动到底部
browser.execute_script(""" 
    (function () { 
        var y = document.body.scrollTop; 
        var step = parseInt(document.body.scrollHeight)/10;
        window.scroll(0, y); 
        function f() {
            console.log("step==>", step);
            if (y < document.body.scrollHeight) { 
                y += step; 
                window.scroll(0, y); 
            }
            else { 
                window.scroll(0, y); 
                document.title += "scroll-done"; 
            } 
        }
        setInterval(f, 1000); 
    })(); 
    """)
print("开始执行向下滚动条")

# 等待15秒钟，等待加载完毕
time.sleep(15)
# 定义js代码
js_code = '''function downloadPages(from, to) { \
    for (i = from; i <= to; i++) { \
        const pageCanvas = document.getElementById('page_' + i); \
        if (pageCanvas === null) { break; } \
        const pageNo = parseInt(String(i)); \
        setTimeout(() => { \
            console.log("==pageNo==>>", pageNo); \
            ((num) => { \
                console.log("开始打印第" + num + "页"); \
                pageCanvas.toBlob( \
                    blob => { \
                        const anchor = document.createElement('a'); \
                        anchor.download = 'page_' + num + '.png'; \
                        anchor.href = URL.createObjectURL(blob); \
                        anchor.click(); \
                        URL.revokeObjectURL(anchor.href); \
                    } \
                ); \
            })(pageNo); \
        }, 500 * pageNo); \
    } \
} \
downloadPages(1, %s)''' % pages  # 数据格式化
browser.execute_script(js_code)  # 执行js代码

print('开始下载')
# 等待20秒钟 等待下载完毕
time.sleep(20)
# 关闭浏览器
browser.close()